package com.yn.iotxiao.authorize;

import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors()
                .and()
                .securityMatcher("/api/login/**","/api/v1/**")
                .authorizeHttpRequests()
                .requestMatchers("/api/login/**","/api/v1/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt();

//        http
//                .authorizeHttpRequests((authorize) -> authorize
//                        // SecurityConstant.IGNORE_PERM_URLS 不需要权限认证
//                        .requestMatchers("/api/**","/login/**","/api/login","/login").permitAll()
//                        // 其他的需要权限认证
//                        .anyRequest().authenticated()
//                )
//                // 资源服务配置秘钥
//                .oauth2ResourceServer().jwt();
        return http.build();
    }

//    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
//    private String jwkSetUri;
private static final String jwkSetUri = System.getenv("IDENTITYSERVER_URI") + "/.well-known/openid-configuration/jwks";

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
                .jwtProcessorCustomizer(customizer -> {
                    customizer.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("at+jwt")));
                })
                .build();
    }
}
